<template>
  <view class="forecast-history-viewer">
    <!-- Loading状态 -->
    <view v-if="loading" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">正在加载预报历史...</text>
    </view>

    <!-- 空状态 -->
    <view v-else-if="!historyData || historyData.length === 0" class="empty-state">
      <text class="empty-icon">📊</text>
      <text class="empty-title">暂无历史记录</text>
      <text class="empty-desc">该水库在指定时段内没有预报记录</text>
    </view>

    <!-- 历史记录展示 -->
    <view v-else class="history-content">
      <!-- 头部信息 -->
      <view class="history-header">
        <view class="header-left">
          <text class="header-icon">🏛️</text>
          <view class="header-info">
            <text class="header-title">{{ stcdName || '水库' }}历史预报记录</text>
            <text class="header-subtitle">{{ historyData.length }} 条记录</text>
          </view>
        </view>
        <view class="header-right">
          <text class="time-badge">{{ startTime }}</text>
        </view>
      </view>

      <!-- 时间轴记录列表 -->
      <view class="timeline-container">
        <view 
          v-for="(record, index) in historyData" 
          :key="record.session_id"
          class="timeline-item"
          :class="{ 'first-item': index === 0 }"
        >
          <!-- 时间轴节点 -->
          <view class="timeline-node">
            <view class="node-dot"></view>
            <view v-if="index < historyData.length - 1" class="node-line"></view>
          </view>

          <!-- 记录卡片 -->
          <view class="record-card">
            <!-- 卡片头部 -->
            <view class="card-header">
              <view class="header-meta">
                <text class="meta-label">📅 创建时间</text>
                <text class="meta-value">{{ record.createdate }}</text>
              </view>
              <view class="header-meta">
                <text class="meta-label">🎯 预报方案</text>
                <text class="meta-value">{{ record.scheme_name || record.model_type }}</text>
              </view>
              <view class="header-meta">
                <text class="meta-label">⏱️ 预报时长</text>
                <text class="meta-value">{{ record.clen }} 小时</text>
              </view>
            </view>

            <!-- 配置摘要 -->
            <view class="card-section config-summary">
              <view class="section-title">
                <text class="title-icon">⚙️</text>
                <text class="title-text">预报配置</text>
              </view>
              <view class="summary-grid">
                <view class="summary-item">
                  <text class="item-label">模型类型</text>
                  <text class="item-value">{{ record.model_type }}</text>
                </view>
                <view class="summary-item">
                  <text class="item-label">起始时间</text>
                  <text class="item-value">{{ record.start_time }}</text>
                </view>
                <view class="summary-item">
                  <text class="item-label">会话ID</text>
                  <text class="item-value session-id">{{ record.session_id.slice(0, 8) }}...</text>
                </view>
              </view>
            </view>

            <!-- 状态对比 -->
            <view class="card-section state-compare" v-if="record.model_states">
              <view class="section-title">
                <text class="title-icon">⚖️</text>
                <text class="title-text">模型状态对比</text>
                <text class="compare-hint">初始 → 最终</text>
              </view>
              <view class="compare-grid">
                <view 
                  v-for="key in Object.keys(record.model_states.initial_state || {})" 
                  :key="key"
                  class="compare-item"
                >
                  <text class="compare-key">{{ key }}</text>
                  <view class="compare-values">
                    <text class="value-initial">{{ formatValue(record.model_states.initial_state[key]) }}</text>
                    <text class="arrow">→</text>
                    <text class="value-final" :class="{ changed: hasChanged(record.model_states.initial_state[key], record.model_states.final_state[key]) }">
                      {{ formatValue(record.model_states.final_state[key]) }}
                    </text>
                  </view>
                </view>
              </view>
            </view>

            <!-- 洪水统计信息 -->
            <view class="card-section flood-stats" v-if="record.flood_statistics">
              <view class="section-title">
                <text class="title-icon">🌊</text>
                <text class="title-text">洪水统计信息</text>
              </view>
              <view class="stats-grid">
                <view class="stat-card">
                  <text class="stat-label">洪水总量</text>
                  <text class="stat-value highlight-blue">{{ record.flood_statistics.flood_volume }}</text>
                  <text class="stat-unit">百万m³</text>
                </view>
                <view class="stat-card">
                  <text class="stat-label">洪峰流量</text>
                  <text class="stat-value highlight-red">{{ record.flood_statistics.peak_discharge }}</text>
                  <text class="stat-unit">m³/s</text>
                </view>
                <view class="stat-card">
                  <text class="stat-label">峰现时间</text>
                  <text class="stat-value highlight-orange">{{ formatPeakTime(record.flood_statistics.peak_time) }}</text>
                  <text class="stat-unit">{{ formatPeakDate(record.flood_statistics.peak_time) }}</text>
                </view>
                <view class="stat-card">
                  <text class="stat-label">预报点数</text>
                  <text class="stat-value highlight-green">{{ record.flood_statistics.forecast_points }}</text>
                  <text class="stat-unit">个</text>
                </view>
              </view>
            </view>

            <!-- 模型参数（最终参数） -->
            <view class="card-section params-display" v-if="record.model_states">
              <view class="section-title">
                <text class="title-icon">🔧</text>
                <text class="title-text">最终模型参数</text>
                <text class="params-count">({{ getParamCount(record.model_states.final_parameters) }})</text>
              </view>
              <view class="params-grid">
                <view 
                  v-for="(value, key) in getModelParameters(record.model_states.final_parameters)" 
                  :key="key"
                  class="param-chip"
                >
                  <text class="chip-key">{{ key }}</text>
                  <text class="chip-value">{{ formatValue(value) }}</text>
                </view>
              </view>
            </view>

            <!-- 预报结果图表 -->
            <view class="card-section chart-display">
              <view class="section-title">
                <text class="title-icon">📈</text>
                <text class="title-text">预报结果可视化</text>
                <text class="chart-info">{{ record.forecast_result.timeSeries?.length || 0 }} 个时间点</text>
              </view>
              <view class="chart-container">
                <!-- 图表占位（需要集成实际图表） -->
                <ForecastChart 
                  v-if="record.forecast_result.timeSeries"
                  :chart-id="'chart_' + record.session_id"
                  :time-series="record.forecast_result.timeSeries"
                  :read-only="true"
                />
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { forecastApi } from '../api/api.js'
import ForecastChart from '../charts/ForecastChart.vue'

export default {
  name: 'ForecastHistory',
  components: {
    ForecastChart
  },
  props: {
    stcd: {
      type: String,
      required: true
    },
    startTime: {
      type: String,
      required: true
    }
  },
  setup(props) {
    const loading = ref(true)
    const historyData = ref([])
    const stcdName = ref('')

    // 加载历史数据
    const loadHistory = async () => {
      try {
        loading.value = true
        const response = await forecastApi.getForecastHistory(props.stcd, props.startTime)
        historyData.value = response.data || []
        if (historyData.value.length > 0) {
          stcdName.value = historyData.value[0].stcd_name || ''
        }
      } catch (error) {
        console.error('加载预报历史失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        loading.value = false
      }
    }

    // 获取模型参数（排除monthlyPET）
    const getModelParameters = (params) => {
      if (!params) return {}
      const { monthlyPET, ...modelParams } = params
      return modelParams
    }

    // 获取参数数量
    const getParamCount = (params) => {
      return Object.keys(getModelParameters(params)).length
    }

    // 格式化数值
    const formatValue = (value) => {
      if (typeof value === 'number') {
        return value.toFixed(3)
      }
      return value
    }

    // 获取状态条宽度（用于可视化）
    const getStateBarWidth = (value) => {
      const maxValue = 100
      const percentage = Math.min((Math.abs(value) / maxValue) * 100, 100)
      return `${percentage}%`
    }

    // 判断值是否发生变化
    const hasChanged = (initialValue, finalValue) => {
      return Math.abs(initialValue - finalValue) > 0.001
    }

    // 格式化峰现时间（只显示时间部分）
    const formatPeakTime = (peakTime) => {
      if (!peakTime) return '-'
      const date = new Date(peakTime.replace(' ', 'T'))
      return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
    }

    // 格式化峰现日期（只显示日期部分）
    const formatPeakDate = (peakTime) => {
      if (!peakTime) return '-'
      const date = new Date(peakTime.replace(' ', 'T'))
      return date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' })
    }

    onMounted(() => {
      loadHistory()
    })

    return {
      loading,
      historyData,
      stcdName,
      getModelParameters,
      getParamCount,
      formatValue,
      getStateBarWidth,
      hasChanged,
      formatPeakTime,
      formatPeakDate
    }
  }
}
</script>

<style scoped>
.forecast-history-viewer {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #0f0c29 0%, #302b63 50%, #24243e 100%);
  overflow-y: auto;
  position: relative;
}

/* Loading */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  gap: 20px;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 4px solid rgba(255, 255, 255, 0.1);
  border-top-color: #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.loading-text {
  color: rgba(255, 255, 255, 0.8);
  font-size: 14px;
}

/* Empty State */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  gap: 16px;
  padding: 40px;
}

.empty-icon {
  font-size: 64px;
  opacity: 0.6;
}

.empty-title {
  color: white;
  font-size: 20px;
  font-weight: 600;
}

.empty-desc {
  color: rgba(255, 255, 255, 0.6);
  font-size: 14px;
  text-align: center;
}

/* History Content */
.history-content {
  padding: 30px 20px;
  max-width: 1400px;
  margin: 0 auto;
}

/* Header */
.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40px;
  padding: 24px;
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  font-size: 48px;
}

.header-info {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.header-title {
  color: white;
  font-size: 24px;
  font-weight: 700;
  letter-spacing: 0.5px;
}

.header-subtitle {
  color: rgba(255, 255, 255, 0.6);
  font-size: 14px;
}

.header-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.time-badge {
  padding: 8px 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 20px;
  color: white;
  font-size: 13px;
  font-weight: 600;
}

/* Timeline */
.timeline-container {
  position: relative;
}

.timeline-item {
  display: flex;
  gap: 24px;
  margin-bottom: 40px;
}

.timeline-item.first-item .node-dot {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  box-shadow: 0 0 20px rgba(102, 126, 234, 0.6);
}

/* Timeline Node */
.timeline-node {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 30px;
}

.node-dot {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.3);
  border: 3px solid rgba(255, 255, 255, 0.5);
  z-index: 2;
  flex-shrink: 0;
}

.node-line {
  width: 2px;
  flex: 1;
  background: linear-gradient(180deg, rgba(255, 255, 255, 0.2) 0%, rgba(255, 255, 255, 0.05) 100%);
  margin-top: 8px;
}

/* Record Card */
.record-card {
  flex: 1;
  background: rgba(255, 255, 255, 0.03);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  overflow: hidden;
  transition: all 0.3s ease;
}

.record-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  border-color: rgba(102, 126, 234, 0.3);
}

/* Card Header */
.card-header {
  display: flex;
  gap: 32px;
  padding: 24px;
  background: rgba(255, 255, 255, 0.02);
  border-bottom: 1px solid rgba(255, 255, 255, 0.05);
}

.header-meta {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.meta-label {
  color: rgba(255, 255, 255, 0.5);
  font-size: 12px;
}

.meta-value {
  color: white;
  font-size: 14px;
  font-weight: 600;
}

/* Card Section */
.card-section {
  padding: 24px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.05);
}

.card-section:last-child {
  border-bottom: none;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
}

.title-icon {
  font-size: 18px;
}

.title-text {
  color: white;
  font-size: 16px;
  font-weight: 600;
}

.params-count,
.chart-info {
  color: rgba(255, 255, 255, 0.4);
  font-size: 12px;
  margin-left: 8px;
}

/* Config Summary */
.summary-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.summary-item {
  display: flex;
  flex-direction: column;
  gap: 6px;
  padding: 12px;
  background: rgba(255, 255, 255, 0.03);
  border-radius: 8px;
  border: 1px solid rgba(255, 255, 255, 0.05);
}

.item-label {
  color: rgba(255, 255, 255, 0.5);
  font-size: 11px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.item-value {
  color: white;
  font-size: 13px;
  font-weight: 500;
  font-family: 'Courier New', monospace;
}

.session-id {
  color: #667eea;
}

/* Params Display */
.params-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.param-chip {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  background: rgba(102, 126, 234, 0.1);
  border: 1px solid rgba(102, 126, 234, 0.2);
  border-radius: 20px;
  transition: all 0.2s ease;
}

.param-chip:hover {
  background: rgba(102, 126, 234, 0.2);
  transform: translateY(-2px);
}

.chip-key {
  color: rgba(255, 255, 255, 0.7);
  font-size: 11px;
  font-weight: 600;
}

.chip-value {
  color: #a5b4fc;
  font-size: 12px;
  font-family: 'Courier New', monospace;
  font-weight: 600;
}

/* State Display */
.state-grid {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.state-item {
  display: flex;
  align-items: center;
  gap: 16px;
}

.state-key {
  color: rgba(255, 255, 255, 0.7);
  font-size: 13px;
  font-weight: 600;
  min-width: 60px;
}

.state-bar-container {
  flex: 1;
  position: relative;
  height: 24px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 12px;
  overflow: hidden;
}

.state-bar {
  height: 100%;
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  transition: width 0.5s ease;
}

.state-value {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: white;
  font-size: 11px;
  font-family: 'Courier New', monospace;
  font-weight: 600;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
}

/* Chart Display */
.chart-container {
  background: rgba(255, 255, 255, 0.02);
  border-radius: 12px;
  padding: 16px;
  min-height: 300px;
}

/* State Compare */
.state-compare {
  background: rgba(138, 180, 248, 0.03);
}

.compare-hint {
  color: rgba(255, 255, 255, 0.4);
  font-size: 11px;
  margin-left: auto;
}

.compare-grid {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.compare-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: rgba(255, 255, 255, 0.03);
  border-radius: 8px;
  border-left: 3px solid rgba(102, 126, 234, 0.5);
}

.compare-key {
  color: rgba(255, 255, 255, 0.8);
  font-size: 14px;
  font-weight: 600;
  min-width: 60px;
}

.compare-values {
  display: flex;
  align-items: center;
  gap: 12px;
}

.value-initial {
  color: rgba(255, 255, 255, 0.5);
  font-size: 13px;
  font-family: 'Courier New', monospace;
}

.arrow {
  color: rgba(255, 255, 255, 0.3);
  font-size: 16px;
}

.value-final {
  color: #a5b4fc;
  font-size: 14px;
  font-family: 'Courier New', monospace;
  font-weight: 600;
}

.value-final.changed {
  color: #fbbf24;
  animation: highlight 2s ease-in-out;
}

@keyframes highlight {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.6;
  }
}

/* Flood Statistics */
.flood-stats {
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.05) 0%, rgba(147, 51, 234, 0.05) 100%);
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 16px;
}

.stat-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 16px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 12px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
  border-color: rgba(102, 126, 234, 0.3);
}

.stat-label {
  color: rgba(255, 255, 255, 0.6);
  font-size: 12px;
  margin-bottom: 8px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  margin-bottom: 4px;
  font-family: 'Courier New', monospace;
}

.stat-value.highlight-blue {
  color: #60a5fa;
  text-shadow: 0 0 20px rgba(96, 165, 250, 0.5);
}

.stat-value.highlight-red {
  color: #f87171;
  text-shadow: 0 0 20px rgba(248, 113, 113, 0.5);
}

.stat-value.highlight-orange {
  color: #fb923c;
  font-size: 18px;
  text-shadow: 0 0 20px rgba(251, 146, 60, 0.5);
}

.stat-value.highlight-green {
  color: #4ade80;
  text-shadow: 0 0 20px rgba(74, 222, 128, 0.5);
}

.stat-unit {
  color: rgba(255, 255, 255, 0.4);
  font-size: 11px;
}
</style>

